package uk.ac.manchester.cs.owl.ontologyrepositoryapi.tools;

import org.semanticweb.owlapi.apibinding.OWLManager;
import org.semanticweb.owlapi.model.*;

import java.io.*;

/**
 * Author: Matthew Horridge<br>
 * The University of Manchester<br>
 * Bio-Health Informatics Group<br>
 * Date: 04/02/2011
 */
public class CheckForErrors {

    private static final String ONTOLOGIES_DIRECTORY_NAME = "ontologies";

        private static final String IMPORTS_DIRECTORY_NAME = "imports";

        private static final String FAILED_TO_LOAD_DIRECTORY_NAME = "failed-to-load";

        private static final String ONTOLOGY_METADATA_PREFIX = "http://owl.cs.manchester.ac.uk/ontology#";

        private static final IRI SOURCE_ONTOLOGY_IRI = IRI.create(ONTOLOGY_METADATA_PREFIX + "sourceOntology");


        public static void main(String[] args) {
            File ontologiesDirectory = new File(ONTOLOGIES_DIRECTORY_NAME);
            if(!ontologiesDirectory.exists()) {
                throw new RuntimeException("Ontologies Directory does not exist");
            }
            for(File ontologyDir : ontologiesDirectory.listFiles()) {
                if(ontologyDir.isDirectory()) {
                    File [] contents = ontologyDir.listFiles();
                    if(contents != null) {
                        for(File content : contents) {
                            if(content.getName().endsWith("owl.xml")) {
                                loadOntology(content);
                            }
                        }
                    }
                }
            }
        }


    private static void loadOntology(File file) {
        try {
            OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
            OWLOntology ont = manager.loadOntologyFromOntologyDocument(file);
//            System.out.println("Processing " + file);
            int errorCount = 0;
            for(OWLClass cls : ont.getClassesInSignature()) {
                if(cls.getIRI().toString().contains("Error")) {
                    errorCount++;
                }
            }
            if(errorCount > 0) {
                System.out.println(file + " contains " + errorCount + " errors");
            }
        }
        catch (OWLOntologyCreationException e) {
            e.printStackTrace();
        }

        catch (RuntimeException e) {
            System.err.println(file);
            e.printStackTrace();
        }

    }


}
